#!/usr/bin/env pyhton
#encoding=utf8

"""
@描述：数据库操作的工具类
@日期：2015年01月29日 星期四

@作者：hongxingfan
"""

import MySQLdb
import sys
import time

class MySQLDB:
	
	'''
	需要有连接，select，insert，update，delete操作
	'''
	# 类变量，私有+全局
	#__CONN = None
	# 构造方法，建立conn对象
	def __init__(self,host,user,passwd,port,charset):
		# 属性赋值
		self.host = host
		self.user = user
		self.passwd = passwd
		self.port = port
		#self.db = db
		self.charset = charset
		self.tryNum = 10
		# 产生conn对象
		self.conn = self.__getConn()

	# 产生conn对象
	def __getConn(self):
		try:
			#global __CONN
			conn = MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,port=self.port,charset=self.charset)
			return conn
		except MySQLdb.Error,e:
			self.tryNum -= 1
			if(self.tryNum > 0):
				print(self.tryNum)
				time.sleep(2)
				self.__getConn()
			else :
				print "Mysql Error %d: %s" % (e.args[0], e.args[1]),
			#print("host:%s" %(self.host))
				sys.exit(0)

	# 查找函数
	def select(self,sql,param):
		try:
			cursor = self.conn.cursor()
			cursor.execute(sql,param)
			result = cursor.fetchall()
			cursor.close()
			return result
		except MySQLdb.Error,e:
			print "Mysql Error %d: %s: %s: %s" % (e.args[0], e.args[1],sql,param)
			#print("host:%s" %(self.host))
			#sys.exit(0)

	# 更新函数
	def update(self,sql,param):
		try:
			cursor = self.conn.cursor()
			n = cursor.execute(sql,param)
			self.conn.commit()
			cursor.close()
			return n
		except MySQLdb.Error, e:
			print "Mysql Error %d: %s: %s: %s" % (e.args[0], e.args[1],sql,param)
			#print("host:%s" %(self.host))
	# 插入函数
	def insert(self,sql,param):
		try:
			cursor = self.conn.cursor()
			n = cursor.execute(sql,param)
			self.conn.commit()
			cursor.close()
			return n
		except MySQLdb.Error, e:
			print "Mysql Error %d: %s: %s: %s" % (e.args[0], e.args[1],sql,param)
			#print("host:%s" %(self.host))
			#print("%s Is Error!" %(sql))
			#sys.exit()
	# 关闭连接
	def close(self):
		self.conn.close()

# 测试程序
if __name__ == "__main__":
	
	# 数据库连接字符串
	host = "127.0.0.1"
	user = "root"
	passwd = ""
	port = 3306
	#db = "fetched"
	charset = "utf8"

	# 获取数据库连接
	selectDB = MySQLDB(host,user,passwd,port,charset)
	param = [37314029] # 注意类型
	result = selectDB.select("SELECT * FROM fetched.jobs WHERE id=%s",param)
	selectDB.close()
	for (id,youhuo) in result:
		print("%d\t%s" %(id,youhuo))
	
	#insertDB = MySQLDB(host,user,passwd,port,charset)
	#insert = "INSERT INTO fetched.jobs(id) VALUES (%s)"
	#param = (("13"),("11"))
	#n = insertDB.insert(insert,param)
	#print(n)
